/**
 * Created by TianShaoKai on 2014/12/10.
 */
var express = require('express');
var bodyParser = require('body-parser');    // Json
var fs = require('fs');
var log4js = require('log4js');             // 日志
var favicon = require('serve-favicon');     // 图标
var cookieParser = require('cookie-parser');// Cookie
var config = require('app-config').config;  // 配置
var debug = require('debug')('CRMSystem');
var path = require('path');
var routes = require('./routes/index');    // 路由
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(cookieParser());                    // Cookie

app.use(session({
    cookie: { maxAge:  60* 60 * 1000 },
    secret: config.session_secret,
    key: 'sid',
    resave: true,
    saveUninitialized:true,
    store: new MongoStore({
        db: config.db_name,
        host: 'localhost',
        username:config.db_seesion_user,
        password:config.db_seesion_pass
    })

}));

log4js.configure({
    appenders: [
        { type: 'console' },    //控制台输出
        {   type: 'file',
            filename: __dirname + '/logs/CRMSystem.log',
            pattern: "-yyyy-MM-dd",
            maxLogSize: 1024 * 1024,
            backups: 5,
            category: 'normal'
        }
    ]
});

var logger = log4js.getLogger('normal');
logger.setLevel('DEBUG');       // ERROR

app.use(log4js.connectLogger(logger,{format:':remote-addr - -' +
    ' ":method :url HTTP/:http-version"' +
    ' :status :content-length ":referrer"' +
    ' ":user-agent" :response-timems'}));

app.use(favicon(__dirname + '/public/favicon.ico'));        // Icon

// 设置view
app.set('view engine', 'html');
app.set('views', __dirname + '/view');
app.engine('.html', require('ejs').__express);


// 因为路由后或请求静态资源后，一次请求响应的生命周期实质上已经结束，加在这后面进行请求处理
app.use(express.static(path.join(__dirname, 'public')));

app.set('port', process.env.PORT || config.port);

//  设置 端口
var server = app.listen(app.get('port'), function() {
    debug('Express server listening on port ' + server.address().port);
});

app.use(routes);
app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') !== 'production') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500).json({
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.json({
        message: err.message,
        error: {}
    });
});


module.exports = app;